<template>
  <j-modal
    :confirmLoading="confirmLoading"
    :ok-button-props="{ props: { disabled: disableSubmit } }"
    :title="title"
    :visible="visible"
    :width="width"
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-if="model.id" :labelCol="labelCol" :wrapperCol="wrapperCol" label="数据ID">
          <a-input v-model="model.id" readOnly/>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="实例设备">
          <j-search-select-tag v-decorator="['instanceId', validatorRules.instanceId]" dict="iot_device_instance,name,id"/>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="数据">
          <a-input v-decorator="['data', validatorRules.data]" placeholder="请输入上报数据"></a-input>
        </a-form-item>
        <a-form-item v-if="model.dataMap" :labelCol="labelCol" :wrapperCol="wrapperCol" label="数据对象">
          <j-code-editor v-model="model.dataMap"></j-code-editor>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="录入方式">
          <a-select v-model="model.reportMode">
            <a-select-option :key="1">上报</a-select-option>
            <a-select-option :key="2">录入</a-select-option>
            <a-select-option :key="3">导入</a-select-option>
          </a-select>
        </a-form-item>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import {httpAction} from '@/api/manage'
import pick from 'lodash.pick'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import JCodeEditor from '@comp/jeecg/JCodeEditor'

export default {
  name: 'DataReportModal',
  components: {
    JCodeEditor,
    JDictSelectTag,
    JSearchSelectTag
  },
  data() {
    return {
      form: this.$form.createForm(this),
      disableSubmit: true,
      title: '操作',
      width: 800,
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        instanceId: {
          rules: [
            {required: true, message: '请输入实例设备!'}
          ]
        },
        data: {
          rules: [
            {required: true, message: '请输入上报数据!', trigger: 'change'},
            {
              validator: (rule, value, callback) => this.isJSON(value),
              message: '请输入JSON格式数据!',
              trigger: 'change'
            }
          ]
        },
        inputMode: {
          rules: [
            { required: true, message: '请输入录入方式!' }
          ]
        }
      },
      url: {
        add: '/message/data/add',
        edit: '/message/data/edit'
      }
    }
  },
  created() {
  },
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      console.log(record)
      this.form.resetFields()
      this.model = Object.assign({reportMode: 2}, record)
      this.model.dataMap = JSON.stringify(record.dataMap, null, '\t')
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'instanceId', 'data', 'dataMap', 'createTime', 'inputMode'))
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          JSON.parse(str)
          return true
        } catch (e) {
          console.log(e)
          return false
        }
      }
      console.log('It is not a string!')
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          console.log('表单提交数据', formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }

      })
    },
    handleCancel() {
      this.close()
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, 'instanceDeviceBy', 'data', 'createTime', 'inputMode'))
    }

  }
}
</script>